<template>
    <!-- 配置菜单权限 -->
    <el-drawer
        v-model="permPoint.visible"
        :title="'权限点分配'"
        @open="handleOpen"
        size="500"
        :close-on-click-modal="false"
    >
        <div class="drawer-main">
            <div class="drawer-header">
                <!--        <el-input v-model="keywords" clearable placeholder="菜单权限名称">-->
                <!--          <template #prefix>-->
                <!--            <el-icon>-->
                <!--              <Search />-->
                <!--            </el-icon>-->
                <!--          </template>-->
                <!--        </el-input>-->
<!--                <el-button-->
<!--                    type="primary"-->
<!--                    plain-->
<!--                    @click="togglePermTree"-->
<!--                    icon="Switch"-->
<!--                    class="ml20"-->
<!--                >-->
<!--                    {{ isExpanded ? '收缩' : '展开' }}-->
<!--                </el-button>-->
                <el-button type="success" icon="Switch" @click="syncPoint">同步</el-button>
            </div>
            <el-scrollbar v-loading="loading">
                <el-tree
                    ref="permTreeRef"
                    node-key="permissionId"
                    show-checkbox
                    :props="defaultProps"
                    :data="permOptions"
                    :filter-node-method="filterNode"
                    :default-expand-all="true"
                    :check-strictly="false"
                />
            </el-scrollbar>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emit('close')">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getMenuTree } from '@views/menuManage/api/menuManage'
import {
    getSyncPoint,
    getSyncPointList,
    addRolePonint,
    getRolePonint
} from '@views/roleManage/api/roleManage'

const props = defineProps({
    permPoint: {
        type: Object,
        default: () => {},
        required: true
    }
})

const loading = ref(false)
const keywords = ref('')
// const defaultProps = { label: 'name', value: 'id', disabled: data => !data.status }
const defaultProps = { label: 'operationDescription', value: 'permissionId' }

const isExpanded = ref(true)
const permTreeRef = ref(null)
const permOptions = ref([])
const emit = defineEmits(['close'])

// 权限筛选
watch(keywords, (val) => {
    permTreeRef.value.filter(val)
})

const handleSave = async () => {
    loading.value = true
    const checkedMenuIds = permTreeRef.value
        .getCheckedNodes(false, true)
        .filter((node) => node.permissionId != null && node.permissionId !== '') // 删除空的、null 或 空字符串的值
        .map((node) => ({ permissionId: node.permissionId })) // 将每个节点的 permissionId 转换为对象形式
    try {
        loading.value = false
        const res = await addRolePonint(
            props.permPoint.row.roleId,
            checkedMenuIds
        )
        if (res.code === 200) {
            ElMessage.success('保存成功')
            emit('close', true)
        }
    } catch (error) {
        console.error('Request error:', error)
    }
}

// 展开/收缩 菜单权限树
// const togglePermTree = () => {
//     isExpanded.value = !isExpanded.value
//     if (permTreeRef.value) {
//         Object.values(permTreeRef.value.store.nodesMap).forEach((node) => {
//             if (isExpanded.value) {
//                 node.expand()
//             } else {
//                 node.collapse()
//             }
//         })
//     }
// }

const filterNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
}

// 获取数据
const getMenuData = async () => {
    loading.value = true
    loading.value = false
    const res = await getSyncPointList()
    if (res.code === 200) {
        const arr = res.data
        const newArr = []
        for (const arrKey in arr) {
            if (arr[arrKey] && arr[arrKey][0]) {
                let newobj = {}
                // 为每个元素的 label 属性赋值
                newobj.operationDescription = arr[arrKey][0].resourceDescription
                newobj.permissionId = ''
                newobj.children = arr[arrKey].slice()
                newArr.push(newobj)
            }
        }
        permOptions.value = newArr
        const getCode = await getRolePonint(props.permPoint.row.roleId)
        if (getCode.code === 200) {
            nextTick(() => {
                console.log(getCode.data)
                const checkedMenuIds = getCode.data || []
                checkedMenuIds.forEach((menuId) => {
                    console.log(menuId)
                    permTreeRef.value.setChecked(menuId, true, false)
                })
            })
        }
    }
}
// 同步权限
const syncPoint = async () => {
    try {
        const res = await getSyncPoint()
        if (res.code === 200) {
            getMenuData()
        }
    } catch (error) {
        console.error('Request error:', error)
    }
}
// 初始化弹窗
const handleOpen = () => {
    getMenuData()

    nextTick(() => {
        permTreeRef.value.setCheckedKeys([]) // 清空选中节点
        console.log('初始化')
    })
}
</script>

<style lang="scss" scoped>
.drawer-main {
    height: 100%;
    display: flex;
    flex-direction: column;

    .drawer-header {
        display: flex;
        margin-bottom: 20px;
    }
}
</style>
